package com.gem.filter;

import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author 刘聪
 * Created  on 2020/10/13
 */
public class WebInterceptor implements HandlerInterceptor {
    /**
     * 登录验证：
     * 拦截所有请求
     * 对于登录请求放行
     * 非登录请求进行登录验证（currUser是否为空）
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String uri = request.getRequestURI();
//        System.out.println(uri);
        if (uri.endsWith("/login") || uri.endsWith("/tologin")) {
            //登录请求 放行
            return true;
        }
        HttpSession session = request.getSession();
        Object user = session.getAttribute("User");
//        System.out.println(user);
        if (user != null) {
            return true;
        }
        response.sendRedirect(request.getContextPath() + "/login");
        return false;
    }
}
